---
import type { MarkdownInstance } from "astro"
import icons from "../assets/icons.svg?url"
import { createDocument, hasIcon } from "../utils"
import { marked } from "marked"

export interface Props {
    html: string | MarkdownInstance<any>
}
const { html } = Astro.props

const formatLink = (a: HTMLElement) => {
    const id = a.innerText.toLowerCase()
    if (hasIcon(id) === false) return

    if (a.getAttribute("href")) a.setAttribute("target", "blank")
    else a.removeAttribute("href")
    a.classList.add("link--icon")

    const noText = id === "pwa"

    const classes = ["icon", `icon--${id}`]

    const className = classes.join(" ")

    const icon = `<svg class="${className}" width="16" height="16"><use href="${icons}#${id}" /></svg>`
    const content = a.innerHTML
    a.innerHTML = noText ? icon : `${icon} ${content}`
    return a
}

const formatHTML = (html: string) => {
    const document = createDocument(html)
    document.querySelectorAll("a").forEach((a) => {
        if (formatLink(a) && a?.parentElement?.tagName?.toLowerCase() == "li")
            a.parentElement.classList.add("li--icon")
    })

    document.querySelectorAll("hr").forEach((hr) => hr.remove())

    // Delete links without href
    let newHtml = document.innerHTML
    document.querySelectorAll("a").forEach((a) => {
        if (a.hasAttribute("href")) return

        const { outerHTML } = a
        newHtml = newHtml.replaceAll(
            outerHTML,
            outerHTML.replaceAll("<a", "<span").replace("</a", "</span"),
        )
    })
    return newHtml
}

const content = formatHTML(
    typeof html === "string" ? html : await marked(html.rawContent()),
)
---

<Fragment set:html={content} />
